package com.carbonspark.ecoquest.domain.service.impl;

import com.carbonspark.ecoquest.common.entity.PageResult;
import com.carbonspark.ecoquest.common.enums.IsCompletedEnum;
import com.carbonspark.ecoquest.common.enums.IsDeletedFlagEnum;
import com.carbonspark.ecoquest.common.enums.IsAbandonedEnum;
import com.carbonspark.ecoquest.domain.convert.TaskBOConverter;
import com.carbonspark.ecoquest.domain.entity.TaskBO;
import com.carbonspark.ecoquest.domain.service.TaskDomainService;

import com.carbonspark.ecoquest.infra.basic.entity.Task;
import com.carbonspark.ecoquest.infra.basic.entity.TaskRules;
import com.carbonspark.ecoquest.infra.basic.entity.TaskUser;
import com.carbonspark.ecoquest.infra.basic.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class TaskDomainServiceImpl implements TaskDomainService {
    @Resource
    private TaskService taskService;

    @Override
    public TaskBO queryById(TaskBO taskBO) {
        Task task = taskService.queryById(taskBO.getId());
        TaskBO result = TaskBOConverter.INSTANCE.convertEntityToBO(task);
        return result;
    }

    @Override
    public TaskBO update(TaskBO taskBO) {
        Task task = TaskBOConverter.INSTANCE.convertBOToEntity(taskBO);
        Task result = taskService.update(task);
        TaskBO bo = TaskBOConverter.INSTANCE.convertEntityToBO(result);

        return bo;
    }

    @Override
    public Boolean deleteById(TaskBO taskBO) {
        Task task = taskService.queryById(taskBO.getId());
        task.setIsDelete(IsDeletedFlagEnum.DELETED.getCode());
        return  taskService.updateStats(task);
    }

    @Override
    public PageResult<TaskBO> selectTaskList(TaskBO taskBO) {
        // 1. 创建分页结果对象，用于返回分页数据
        PageResult<TaskBO> pageResult = new PageResult<>();

        // 2. 设置分页结果的当前页码和每页大小
        pageResult.setPageNo(taskBO.getPageNo());
        pageResult.setPageSize(taskBO.getPageSize());

        // 3. 计算查询的起始位置 (start)，公式为：(当前页码 - 1) * 每页大小
        int start = (taskBO.getPageNo() - 1) * taskBO.getPageSize();

        // 4. 查询符合条件的总记录数
        int count = taskService.countByCondition();

        // 5. 如果总记录数为 0，直接返回空的分页结果

        // 6. 根据起始位置和每页大小查询任务列表
        List<Task> taskList = taskService.selectTaskList(start, taskBO.getPageSize(),taskBO.getTaskStatus(),
                taskBO.getTaskDifficulty(),
                taskBO.getCategoryId());

        // 7. 将任务实体列表转换为业务对象列表
        List<TaskBO> taskBOS = TaskBOConverter.INSTANCE.convertEntityListToBOList(taskList);

        // 8. 将转换后的业务对象列表设置到分页结果中
        pageResult.setRecords(taskBOS);

        // 9. 将总记录数设置到分页结果中
        pageResult.setTotal(count);

        // 10. 返回最终的分页结果
        return pageResult;
    }




}
